package net.xdclass.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.xdclass.enums.CouponCategoryEnum;
import net.xdclass.enums.CouponPublisEnum;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.model.LoginUser;
import net.xdclass.request.NewUserCouponRequest;
import net.xdclass.service.CouponService;
import net.xdclass.until.JsonData;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 二当家小D
 * @since 2022-02-08
 */
@Api("优惠券模块")
@RestController
@RequestMapping("/api/coupon/v1")
public class CouponController {

    @Autowired
    private CouponService couponService;
    @Autowired
    private RedissonClient redissonClient;

    @ApiOperation("分页查询优惠券")
    @GetMapping("page_coupon")
    public JsonData pageCouponList(
            @ApiParam(value = "当前页")
            @RequestParam(value = "page", defaultValue = "1") int page,
            @ApiParam(value = "每页多少条")
            @RequestParam(value = "size", defaultValue = "10") int size
    ) {
        Map<String, Object> stringObjectMap = couponService.pageCouponActivity(page, size);
        return JsonData.buildSuccess(stringObjectMap);
    }

    @ApiOperation("领取优惠券")
    @GetMapping("/add/promotion/{coupon_id}")
    public JsonData addPromotionCoupon(@ApiParam(value = "优惠券id", required = true)
                                       @PathVariable("coupon_id") long couponId) {
        LoginUser loginUser = LoginInterceptor.loginUserThreadLocal.get();
        String lockKey = "lock:coupon:" + couponId + ":" + loginUser.getId();
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock();
        try {
            JsonData data = couponService.addCoupon(couponId, CouponCategoryEnum.PROMOTION);
            return JsonData.buildSuccess(data);
        } finally {
            rLock.unlock();
        }
    }

    @ApiOperation("RPC-新用户注册接口")
    @PostMapping("/new_user_coupon")
    public JsonData addNewUserCoupon(@ApiParam("用户对象") @RequestBody NewUserCouponRequest newUserCouponRequest) {
        JsonData jsonData = couponService.initNewUserCoupon(newUserCouponRequest);
        return JsonData.buildSuccess(jsonData);
    }
}

